// pages/myInfo/myInfo.js
const util = require('../../utils/util.js')
import * as utils from '../../utils/util.js'
import request from '../../utils/http.js'
import Toast from '@vant/weapp/toast/toast';
import upload from '../../utils/upload.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId:'',
    name:'昵称',
    nameError:'',
    babyheadImg:'/images/child-portrait.png',
    phone:'',
    occupation:'',
    job:'请选择职业',
    jobList:[],
    birthday:'请选择生日',
    areaId:'',
    userArea: '请选择地区',
    address:'',
    province: '',
    city: '',
    counties: '',
    title:'我的资料',
    birthdayshow:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    showJob:false,
    showArea:false,
    formatter(type, value){
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }else{
        return `${value}日`;
      }
    },
    areaList: {},//省市区列表
  },
  uploadBabyImg(){//选择宝宝头像
    let that = this;
      wx.chooseImage({
        count:1,
        sourceType: ['album', 'camera'],
        success(res){
          let imgpath = res.tempFilePaths[0];
          wx.navigateTo({
            url: '/pages/cut-pictures/cut-pictures?src=' + imgpath,
          })
        },
        fail(err){
        },
      })
    },
  submit(){
    if (this.data.nameError == '' && this.data.name!=''){
      wx.showLoading();
    //发送数据给服务器
        let tempFilePath = this.data.babyheadImg;
        upload(tempFilePath, "pic_root").then(res => {
          if(res.status){
            let bir = this.data.birthday
            if (bir == '请选择生日') {
              bir = ''
            }
            var data = {
              userId: this.data.userId,
              name: this.data.name,
              birthday: bir,
              occupation: this.data.occupation,
              areaId: this.data.areaId,
              address: this.data.address,
              avatar: res.url
            }
            utils.HttpRequst(false, "/baby-cloud-system/mobileUser/edit", "post", data, (res) => {
              if (res.data.code == 200) {
                Toast("修改成功")
                this.getUserInfo()
              } else {
                Toast(res.data.message)
              }
              wx.hideLoading();
            })
          }
        }, err => {
          let bir = this.data.birthday
          if (bir == '请选择生日') {
            bir = ''
          }
          var data = {
            userId: this.data.userId,
            name: this.data.name,
            birthday: bir,
            occupation: this.data.occupation,
            areaId: this.data.areaId,
            address: this.data.address,
            avatar: this.data.babyheadImg
          }
          utils.HttpRequst(false, "/baby-cloud-system/mobileUser/edit", "post", data, (res) => {
            if (res.data.code == 200) {
              Toast("修改成功")
              this.getUserInfo()
            } else {
              Toast(res.data.message)
            }
            wx.hideLoading();
          })
        })
    } else if (this.data.nameError != ''){
      Toast(this.data.nameError)
    } 
  },
  nameInput(e) {
    let username = e.detail
    this.setData({
      name: username
    })
  },
  clearName(){
    this.setData({
      nameError: "请输入昵称",
      name:''
    })
    Toast(this.data.nameError)
  },
  //校验昵称
  checkName(e) {
    console.log(e.detail.value)
    let name = e.detail.value
    let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g;
    if (reg.test(name)) {
      this.setData({
        nameError: "昵称中不能有特殊符号哦，请您检查输入的内容"
      })
    }else if (name.length =='') {
      this.setData({
        nameError: "请输入昵称"
      })
      Toast(this.data.nameError)
    } else if (name.length>20) {
      this.setData({
        nameError: "昵称长度为1-20个字符之间"
      })
      Toast(this.data.nameError)
    } else {
      this.setData({
        nameError: ""
      })
    }
  },
  changeArea(){
    this.setData({
      showArea: true
    })
  },
  complateSelArea(e) {
    console.log(e)
    let arealist = e.detail.values;
    // let areaids = arealist.values;
    console.log(arealist)
    let str = '';
    arealist.forEach((item) => {
      str = str + item.name;
    })
    this.setData({
      userArea: str,
      areaId: arealist[2].code,
      address: arealist[0].name + ',' + arealist[1].name + ',' + arealist[2].name
    })
    //处理完成关闭弹窗
    this.onCloseArea();
  },
  cancel() {//选接种地区关闭
    //处理完成关闭弹窗
    this.onCloseArea();
  },
  onCloseArea(){
    this.setData({
      showArea: false
    })
  },
  getArea() {//获取地区列表
    utils.HttpRequst(true, "/baby-cloud-base/area/selectAreaListByH5", "post", {}, (res) => {
      if (res.data.code == 200) {
        this.setData({
          areaList: res.data.data
        })
      }
    })
  },
  //修改职业
  changeJob() {
    this.setData({
      showJob: true
    })
  },
  onSelect(e){
    console.log(e.detail)
    let data = e.detail
    this.setData({
      occupation:data.value,
      job:data.name,
      showJob: false
    })
  },
  
  onClose() {//职业弹窗
    this.setData({
      showJob: false
    })
  },
  changeBirthday() {//生日弹窗
    this.setData({
      birthdayshow: true
    })
  },
  onClosebirthday() {//关闭生日弹窗
    this.setData({
      birthdayshow: false,
    })
  },
  //确认生日
  birthdayComfirm(e) {
    console.log(e)
    let dateStr = utils.format(new Date(e.detail));
    let date = new Date(dateStr)
    this.setData({
      birthday: dateStr,
      currentDate: date,
      birthdayshow: false
    })
  },
  birthdayCancel() {
    this.setData({
      birthdayshow: false
    })
  },
  back() {
    let userInfo=wx.getStorageSync('userInfo')
    let bir=userInfo.birthday.split(' ')[0]
    let area = userInfo.address.split(',').join('')
    if(bir==''){
      bir = "请选择生日"
    }
    if(area==''){
      area = "请选择地区"
    }
    console.log(userInfo)
    console.log(this.data)
    if (userInfo.name != this.data.name || userInfo.avatar != this.data.babyheadImg || bir != this.data.birthday || userInfo.occupation != this.data.occupation || area != this.data.userArea){
      wx.showModal({
        title: '提示',
        content: '您的修改还未保存，是否放弃本次修改？',
        success(res1) {
          if (res1.confirm) {
            let pages = getCurrentPages();
            let beforePage = pages[pages.length - 2]; // -2 是上一个页面，-3是上上个页面以此类推。
            wx.navigateBack({//返回
              delta: 1
            })
          }
        }
      })
    }else{
      let pages = getCurrentPages();
      let beforePage = pages[pages.length - 2]; // -2 是上一个页面，-3是上上个页面以此类推。
      wx.navigateBack({//返回
        delta: 1
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取家庭关系列表
    this.getUserInfo()
    this.getArea()
  },
  getUserInfo(){
    let dict = wx.getStorageSync("dict");
    let jobList = dict["occupation"].data;
    utils.HttpRequst(true, "/baby-cloud-system/mobileUser/getUserDetail", "post", {}, (res) => {
      wx.setStorageSync('userInfo', res.data.data)
      let data = res.data.data
      let phone = data.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      let birthday = ""
      let bir = ''
      let cBir = ''
      let beforeEighteenYear = new Date().getTime() - 18 * 365 * 24 * 60 * 60 * 1000;
      let minBirthday = new Date().getTime() - 100 * 365 * 24 * 60 * 60 * 1000;
      if (data.birthday == '') {//未设置生日
        birthday = "请选择生日"
        cBir = beforeEighteenYear
      } else {
        birthday = data.birthday.split(" ")[0]
        let mydate = new Date(birthday)
        cBir = mydate.getTime()
      }
      let occupation = data.occupation
      let job = "请选择职业"
      let area = "请选择地区"
      let areaId = data.areaId
      if (occupation == '') {
        job = "请选择职业"
      } else {
        jobList.forEach(item => {
          if (item.value == occupation) {
            job = item.name
          }
        })
      }
      if (areaId == '') {
        area = "请选择地区"
      }else{
        area = data.address.split(',').join('')
      }
      console.log(data)
      this.setData({
        userId: data.userId,
        jobList: jobList,
        babyheadImg: data.avatar,//头像
        name: data.name,
        phone: phone,
        birthday: birthday,
        currentDate:  cBir,
        maxDate: beforeEighteenYear,
        minDate: minBirthday,
        occupation: occupation,//职业编码
        job: job,
        areaId: areaId,//三级地区
        userArea: area,
        address: data.address,
        wxNotice: data.wxNotice,//微信通知
        smsNotice: data.smsNotice,//短信通知
      })
    })
  },
  getMaxDate(){
    let date = new Date()
    let strYear = date.getFullYear() - 18;
    let strDay = date.getDate();
    let strMonth = date.getMonth() + 1;  
    let day=''
    if (strMonth < 10) {
        strMonth ="0"+strMonth;
    }
    if (strDay < 10)  {
        strDay ="0"+strDay;
    }
    day = strYear + "-" + strMonth + "-" + strDay;
    let date1 = new Date(day)
    this.setData({
      maxDate: date1.getTime()
    })
    console.log(date1)
  }
})